package com.novice.mq.helloworld;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerTest {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1、创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //1-1、设置连接工厂的参数
        connectionFactory.setHost("47.109.145.220");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("itcast");
        connectionFactory.setPassword("123321");
        //1-2、通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        //2、通过连接创建通道
        Channel channel = connection.createChannel();
        //3、创建队列
        String queueName = "simple.queue";
        channel.queueDeclare(queueName, false, false, false, null);
        //4、订阅消息队列
        channel.basicConsume(queueName,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 5、处理消息
                String msg = new String(body);
                System.out.println("消费者收到消息：" + msg);
            }
        });
    }
}
